package com.liankuan.console.controller.vo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.liankuan.console.dto.Exchange;
import com.liankuan.console.dto.Strategy;
import com.liankuan.console.dto.StrategyExchange;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
public class StrategyVO {
    private Integer id;
    private String name;
    private String jarName;
    private Integer state;
    private String email;
    private String params;
    private List<ExchangeVO> exchanges;
    private JSONArray config;
    private Integer jarIsUpdate;

    public StrategyVO() {
    }

    public StrategyVO(Strategy strategy, List<StrategyExchange> Sexchanges, List<Exchange> exchanges, String
            jarIsUpdate) {
        if (strategy != null) {
            this.id = strategy.getId();
            this.name = strategy.getName();
            this.jarName = strategy.getJarName();
            this.state = strategy.getState();
            this.config = parameterList(strategy);
            this.params = strategy.getParams();
            this.email = strategy.getEmail();
            this.jarIsUpdate = getJarIsUpdate(jarIsUpdate);
        }

        this.exchanges = getExchangeVOList(exchanges, Sexchanges);
    }

    /**
     * 获取该策略合并信息后的交易所数据
     *
     * @param exchanges
     * @param list
     * @return
     */
    private List<ExchangeVO> getExchangeVOList(List<Exchange> exchanges, List<StrategyExchange> list) {
        //获取关联表中策略对应的所有交易所的所得交易对信息
        Map<Integer, StrategyExchange> map = list.stream().collect(Collectors.toMap
                (StrategyExchange::getExchangeId, Function.identity()));

        //完善该策略对应的交易所的数据
        return exchanges.stream().map(record -> {
            StrategyExchange strategyExchange = map.get(record.getId());
            return new ExchangeVO(record, strategyExchange);
        }).collect(Collectors.toList());
    }

    /**
     * 获取jar包是否有更新的状态
     *
     * @param jarUpdateState
     * @return
     */
    private Integer getJarIsUpdate(String jarUpdateState) {
        if ("UPDATE".equals(jarUpdateState)) {
            return 1;
        }

        return 0;
    }


    /**
     * 将配置的参数转换为对象
     *
     * @param strategy
     * @return
     */
    private JSONArray parameterList(Strategy strategy) {
        return JSON.parseArray(strategy.getConfig());
    }
}
